package batch_processing;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Batch {
	// JDBC driver name and database URL
	   static final String JDBC_DRIVER = "org.sqlite.JDBC";  
	   static final String DB_URL = "jdbc:sqlite:d:/db/sqlite/test.db";
	public static void main(String[] args) {
		 
		   
		   try {
			   Class.forName(JDBC_DRIVER);
		   }catch (ClassNotFoundException ex){
			   ex.printStackTrace();
		   }
		   
		   String [] queries = {
				    "INSERT INTO emp VALUES (NULL,38, 'John', 'Ibrahim')",
				    "INSERT INTO emp VALUES (NULL,38, 'Paul', NULL)",
				    "INSERT INTO emp VALUES (NULL,38, 'Alf', NULL)",
				    "INSERT INTO emp VALUES (NULL,38, 'Albert', NULL)"
				};
		   try (Connection con = DriverManager.getConnection(DB_URL);
				   Statement stm = con.createStatement();) {
		      
			   
			   /*
			    * BAD code
			    * for (String query : queries) {
				    statement.execute(query);
				  }
				  
				  You are executing each query separately.
				  This hits the database for each insert statement.
				  Consider if you want to insert 1000 records. This is not a good idea.
			    */
			   
			   // Good Code
			   for (String query : queries) {
				    stm.addBatch(query);
				}
			   
			   // Create an int[] to hold returned values
			   int[] count = stm.executeBatch();
			   
				stm.close();
				con.close();
			   
			   for (int i : count){
				   System.out.println(i);
			   }
		   }catch(SQLException se){
		      //Handle errors for JDBC
		      se.printStackTrace();
		   }
		   
		   System.out.println("Goodbye!");

	}
}
